package cn.wenjie.gd.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import cn.wenjie.gd.domain.Collection;
import cn.wenjie.gd.domain.CollectionSub;
import cn.wenjie.gd.domain.Medical;
import cn.wenjie.gd.domain.PayType;
import cn.wenjie.gd.domain.Role;
import cn.wenjie.gd.domain.User;
import cn.wenjie.gd.service.CollectionService;
import cn.wenjie.gd.service.CollectionServiceImp;
import cn.wenjie.gd.service.CollectionSubService;
import cn.wenjie.gd.service.CollectionSubServiceImp;
import cn.wenjie.gd.service.MedicalService;
import cn.wenjie.gd.service.MedicalServiceImp;
import cn.wenjie.gd.service.UserService;
import cn.wenjie.gd.service.UserServiceImp;
import cn.wenjie.gd.util.CollectionPage;
import cn.wenjie.gd.util.MedicalPage;
import cn.wj.base.annotation.Packing;
import cn.wj.base.annotation.RequestMapping;
import cn.wj.base.controller.BaseController;
import cn.wj.base.util.AdviceImp;
import cn.wj.base.util.Page;
import cn.wj.base.util.ProxyUtil;

@WebServlet("/sell")
public class SellController extends BaseController {
	private CollectionService collectionService = ProxyUtil.getProx(new CollectionServiceImp(), new AdviceImp());
	
	private CollectionSubService collectionSubService = ProxyUtil.getProx(new CollectionSubServiceImp(), new AdviceImp());
	
	private MedicalService medicalService = ProxyUtil.getProx(new MedicalServiceImp(), new AdviceImp());

	private UserService userService= ProxyUtil.getProx(new UserServiceImp(),new AdviceImp());
	
	@RequestMapping(method = "toAdd")
	public String toAdd(HttpServletRequest request, HttpServletResponse response) {
		List<User> memberList=userService.getAllMember();
		addAttribute("memberList", memberList);
		
		List<PayType> payTypeList=collectionService.getAllPayType();
		addAttribute("payTypeList", payTypeList);
		
		List<Medical> medicalList=medicalService.getAllEffective();
		addAttribute("medicalList", medicalList);
		
		return "/pages/sell/add.jsp";
	}

	@RequestMapping(method = "add",auto=false)
	public String add(@Packing(name = "collection", type = Collection.class) Collection collection,@Packing(name = "collectionSub", type = CollectionSub[].class) CollectionSub[] collectionSub,HttpServletRequest request, HttpServletResponse response) throws IOException {
		collection.setDate(new Date());
		collectionService.save(collection);
		User user=userService.getById(collection.getClientId());
		user.setPoint( user.getPoint()+collection.getAmount() );
		userService.update(user);
		double count=0;
		StringBuffer buffer=new StringBuffer();
		for(CollectionSub c:collectionSub){
			c.setCollectionId(collection.getId());
			count+=c.getQuantity()*c.getCost();
			collectionSubService.save(c);
			buffer.append(",");
			buffer.append(c.getMedicalId());
		}
		collection.setMcost(count);
		collection.setMark(2);
		collectionService.update(collection);
		
		List<Medical> medicalList = medicalService.getByIds(buffer.toString().substring(1));
		for(Medical m:medicalList){
			for(CollectionSub c:collectionSub){
				 if(m.getId().equals(c.getMedicalId())){
					 m.setAmount(m.getAmount()-c.getQuantity());
				 }
			}
			medicalService.update(m);
		}
			
		response.sendRedirect(request.getContextPath()+"/sell/toAdd.do");
		return null;
	}
	
	@RequestMapping(method = "delete",auto=false)
	public String delete(@Packing(name = "id", type = Integer.class) Integer id,HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<CollectionSub> collectionSubList =collectionSubService.getByCollectionId(id);
		StringBuffer medicalIds=new StringBuffer();
		for(CollectionSub c4:collectionSubList){
			medicalIds.append(",");
			medicalIds.append(c4.getMedicalId());
			collectionSubService.delete(c4.getId()); 
		}
		//还原药品的数量
		List<Medical> medicalList = medicalService.getByIds(medicalIds.toString().substring(1));
		for(Medical m:medicalList){
			for(CollectionSub c:collectionSubList){
				 if(m.getId().equals(c.getMedicalId())){
					 m.setAmount(m.getAmount()+c.getQuantity());
				 }
			}
			medicalService.update(m);
		}
		
		collectionService.delete(id);
		response.sendRedirect(request.getContextPath()+"/sell/list.do");
		return null;
	}

	@RequestMapping(method = "toUpdate")
	public String toUpdate(@Packing(name = "id", type = Integer.class) Integer id,HttpServletRequest request, HttpServletResponse response) throws IOException {
		Collection collection=collectionService.getById(id);
		addAttribute("collection", collection);
		List<CollectionSub> collectionSubList =collectionSubService.getByCollectionId(collection.getId());
		addAttribute("collectionSubList", collectionSubList);
		List<User> memberList=userService.getAllMember();
		addAttribute("memberList", memberList);
		
		List<PayType> payTypeList=collectionService.getAllPayType();
		addAttribute("payTypeList", payTypeList);
		
		List<Medical> medicalList=medicalService.getAllEffective();
		List<Medical> medicalList2=new ArrayList<Medical>();
		medicalList2.addAll(medicalList);
		
		Iterator<Medical> sListIterator = medicalList.iterator();  
		while(sListIterator.hasNext()){  
			Medical m = sListIterator.next();  
			for(CollectionSub c:collectionSubList){
				if(m.getId()==c.getMedicalId()){
					sListIterator.remove();  
					
				}
			}
		}  
		addAttribute("medicalList2", medicalList2);
		addAttribute("medicalList", medicalList);
		return "/pages/sell/update.jsp";
	}
	
	@RequestMapping(method = "show")
	public String show(@Packing(name = "id", type = Integer.class) Integer id,HttpServletRequest request, HttpServletResponse response) throws IOException {
		Collection collection=collectionService.getById(id);
		addAttribute("collection", collection);
		List<CollectionSub> collectionSubList =collectionSubService.getByCollectionId(collection.getId());
		addAttribute("collectionSubList", collectionSubList);
		List<User> memberList=userService.getAllMember();
		addAttribute("memberList", memberList);
		
		List<PayType> payTypeList=collectionService.getAllPayType();
		addAttribute("payTypeList", payTypeList);
		
		List<Medical> medicalList=medicalService.getAll();
		addAttribute("medicalList", medicalList);
		return "/pages/sell/show.jsp";
	}
	
	@RequestMapping(method = "update",auto=false)
	public String update(@Packing(name = "collection", type = Collection.class) Collection collection,
			@Packing(name = "cId", type = Integer.class) Integer cId,
			@Packing(name = "collectionSub", type = CollectionSub[].class) CollectionSub[] collectionSubs,HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		Collection cl=collectionService.getById(cId);
		collection.setMark(cl.getMark());;
		collection.setDate(new Date());
		collection.setId(cId);
		User user=userService.getById(collection.getClientId());
		
		List<CollectionSub> deleteList=new ArrayList<CollectionSub>();
		List<CollectionSub> collectionSubList =collectionSubService.getByCollectionId(collection.getId());
		StringBuffer medicalIds=new StringBuffer();
		for(CollectionSub c1:collectionSubList){
			medicalIds.append(",");
			medicalIds.append(c1.getMedicalId());
			boolean mark=true;
			for(CollectionSub c2:collectionSubs){
				if(c1.getId().equals(c2.getId())){
					mark=false;
					continue;
				}
			}
			if(mark){
				deleteList.add(c1);
			}
		}
		//还原药品的数量
		List<Medical> medicalList = medicalService.getByIds(medicalIds.toString().substring(1));
		for(Medical m:medicalList){
			for(CollectionSub c:collectionSubList){
				 if(m.getId().equals(c.getMedicalId())){
					 m.setAmount(m.getAmount()+c.getQuantity());
					 user.setPoint( user.getPoint()-c.getTotal() );
				 }
			}
		}
		//修改减去卖出药品的数量
		for(Medical m:medicalList){
			for(CollectionSub c:collectionSubs){
				if(m.getId().equals(c.getMedicalId())){
					m.setAmount(m.getAmount()-c.getQuantity());
				}
			}
			medicalService.update(m);
		}
		double count=0;
		for(CollectionSub c3:collectionSubs){
			count+=c3.getQuantity()*c3.getCost();
			if(c3.getId()!=null){ 
				collectionSubService.update(c3); 
			} else {
				c3.setCollectionId(cId);
				collectionSubService.save(c3); 
			}
		}
		collection.setMcost(count);
		collectionService.update(collection);
		
		for(CollectionSub c4:deleteList){
			collectionSubService.delete(c4.getId()); 
		}
		user.setPoint( user.getPoint()+collection.getAmount() );
		userService.update(user);
		response.sendRedirect(request.getContextPath()+"/sell/list.do");
		return null;
	}
	
	@RequestMapping(method = "list")
	public String list(@Packing(name = "page", type = CollectionPage.class) CollectionPage page,HttpServletRequest request, HttpServletResponse response) {
		page.setUrl(request.getRequestURI());
		String strpageSize= request.getParameter("pageSize");
		if(strpageSize!=null && !strpageSize.equals("")) page.setPageSize(Integer.parseInt(strpageSize));
		String strpageNum= request.getParameter("pageNum");
		if(strpageNum!=null && !strpageNum.equals("")) page.setPageNum(Integer.parseInt(strpageNum));
		
		Page pagelist=collectionService.getPage(page);
		List<PayType> payTypeList=collectionService.getAllPayType();
		addAttribute("payTypeList", payTypeList);
		addAttribute("page", pagelist);
		return "/pages/sell/list.jsp";
	}

	@RequestMapping(method="getMedical",auto=false,isAjax=true)
	public String getMedical(@Packing(name = "medicalId", type = Integer.class) Integer medicalId,HttpServletRequest request, HttpServletResponse response){
		Medical medical=medicalService.getById(medicalId);
		Gson gson=new Gson();
		return gson.toJson(medical);
	}
	
	 
	@RequestMapping(method = "transfer")
	public String transfer(@Packing(name = "page", type = CollectionPage.class) CollectionPage page,
			@Packing(name = "ids", type = Integer[].class) Integer[] ids,
			HttpServletRequest request, HttpServletResponse response) {
		if(ids!=null && ids.length>0){
			for(Integer id:ids){
				Collection c=collectionService.getById(id);
				if(c.getMark()==1){
					 c.setMark(2);
				}else if(c.getMark()==2){
					 c.setMark(1);
				}
				collectionService.update(c);
			}
		}
		
		page.setUrl(request.getRequestURI());
		String strpageSize= request.getParameter("pageSize");
		if(strpageSize!=null && !strpageSize.equals("")) page.setPageSize(Integer.parseInt(strpageSize));
		String strpageNum= request.getParameter("pageNum");
		if(strpageNum!=null && !strpageNum.equals("")) page.setPageNum(Integer.parseInt(strpageNum));
		
		Page pagelist=collectionService.getPage(page);
		List<PayType> payTypeList=collectionService.getAllPayType();
		addAttribute("payTypeList", payTypeList);
		addAttribute("page", pagelist);
		return "/pages/sell/transfer.jsp";
	}
}
